<template>
	<!-- 图片上传 -->
	<view>
		<u-upload accept="media" :width="width" :height="height" :previewFullImage="previewFullImage"
			:fileList="fileList2" @afterRead="afterReadPic" @delete="deletePic" name="2" multiple :maxCount="maxCount">
			<image :src="imgUrl" :style="{'width': width +'px', 'height': height +'px'}" mode="">
			</image>
		</u-upload>
	</view>
</template>

<script>
	import {
		BaseURL
	} from '@/utils/global.js'
	export default {
		name: "ImgUpload",
		data() {
			return {
				fileList2: [], // 文件列表
				show: true,
			};
		},
		props: {
			// 宽度 px
			width: {
				type: Number,
				default: 100
			},
			// 高度 px
			height: {
				type: Number,
				default: 100
			},
			// 是否可文件预览
			previewFullImage: {
				type: Boolean,
				default: true
			},
			// 最大上传数量
			maxCount: {
				type: Number,
				default: 9
			},
			// 背景图片
			imgUrl: {
				type: String,
				default: 'http://qiniu.suboshimuying.cn/static/user/wei.png'
			},
			// 回显图片
			playback: {
				type: Array,
			}
		},
		created() {
			uni.$on("imgListClear", () => {
				this.fileList2 = []
			})
		},
		watch: {
			playback(newVal, oldVal) {
				console.log(newVal)
				if (newVal) {
					this.fileList2 = newVal
				}
			}
		},
		methods: {
			// 新增图片
			async afterReadPic(event) {
				console.log(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				// console.log(this.fileList2);
				let fileList2Len = this.fileList2.length
				lists.map((item) => {
					this.fileList2.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					const newRes = JSON.parse(result).data
					// console.log(newRes);
					let item = this.fileList2[fileList2Len]
					this.fileList2.splice(fileList2Len, 1, Object.assign(item, {
						status: 'success',
						message: '',
						...newRes
					}))
					// console.log('上传后的文件', this.fileList2);
					this.$emit('callback', this.fileList2)
					fileList2Len++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: BaseURL + '/api/common/upload',
						filePath: url,
						name: 'file',
						formData: {
							'type': 'image'
						},
						// header: {
						// 	'X-Access-Token': uni.getStorageSync('token')
						// },
						success: (res) => {
							// console.log('上传成功回调', res);
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
						}
					});
				})
			},
			// 删除图片
			deletePic(event) {
				this.fileList2.splice(event.index, 1)
				this.$emit('callback', this.fileList2)
				// console.log(this.fileList2);
			},
		},
	}
</script>


<style lang="scss" scoped>

</style>
